package com.bjpowernode.app.configuration;
import com.bjpowernode.app.filter.MyLogoutFilter;
import com.bjpowernode.app.realm.MyRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm() {
        MyRealm myRealm = new MyRealm();
        return myRealm;
    }

    @Bean
    public SecurityManager securityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
        //anon: 无需认证即可访问
        //authc: 需要认证才可访问
        //user: 点击“记住我”功能可访问
        //perms: 拥有权限才可以访问
        //role: 拥有某个角色权限才能访问
        //DefaultFilter
//      PermissionsAuthorizationFilter
        linkedHashMap.put("/admin/index", "perms[admin:index]");
        linkedHashMap.put("/admin/index2", "perms[admin:index2]");
        linkedHashMap.put("/logout", "logoutFilter");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);

        shiroFilterFactoryBean.setUnauthorizedUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/admin/index");
        shiroFilterFactoryBean.setLoginUrl("/login");
        return shiroFilterFactoryBean;
    }

    //Spring注册过滤器bean
    @Bean
    public FilterRegistrationBean filterRegistrationBean(MyLogoutFilter logoutFilter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(logoutFilter);
        filterRegistrationBean.setEnabled(false);
        return filterRegistrationBean;
    }

    //ShiroFilterFactoryBean中的linkedHashMap中的value认的是bean-id
    @Bean
    public MyLogoutFilter logoutFilter() {
        return new MyLogoutFilter();
    }
}